package map_set.leetcode.medium;

import java.util.HashMap;
import java.util.Map;

/**
 * @author bruin_du
 * @description 最近最少使用缓存
 * @date 2022/8/12 19:49
 **/
public class OfferII031_LRUCache {
    public class Node {
        public int key;
        public int value;
        public Node prev;
        public Node next;

        public Node() {}

        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }
    Map<Integer, Node> map;
    Node dummyHead, dummyTail;
    int capacity;
    public OfferII031_LRUCache(int capacity) {
        map = new HashMap<>(capacity);
        this.capacity = capacity;
        dummyHead = new Node();
        dummyTail = new Node();
        dummyHead.next = dummyTail;
        dummyTail.prev = dummyHead;
    }

    public int get(int key) {
        if (!map.containsKey(key)) return -1;
        else {
            Node node = map.get(key);
            moveToTail(node);
            return node.value;
        }
    }

    public void put(int key, int value) {
        if (map.containsKey(key)) {
            Node node = map.get(key);
            node.value = value;
            moveToTail(node);
        } else {
            if (map.size() == capacity) {
                Node node = dummyHead.next;
                dummyHead.next = node.next;
                dummyHead.next.prev = dummyHead;
                node.next = null;
                node.prev = null;
                insertNode(key, value);
                map.remove(node.key);
            } else {
                insertNode(key, value);
            }
        }
    }

    private void moveToTail(Node node) {
        node.prev.next = node.next;
        node.next.prev = node.prev;
        dummyTail.prev.next = node;
        node.prev = dummyTail.prev;
        node.next = dummyTail;
        dummyTail.prev = node;
    }

    private void insertNode(int key, int value) {
        Node newNode = new Node(key, value);
        Node node = dummyTail.prev;
        node.next = newNode;
        newNode.prev = node;
        newNode.next = dummyTail;
        dummyTail.prev = newNode;
        map.put(key, newNode);
    }

    public static void main(String[] args) {
        OfferII031_LRUCache offer = new OfferII031_LRUCache(2);
        offer.put(1, 1);
        offer.put(2, 2);
        System.out.println(offer.get(1));
        offer.put(3, 3);
        System.out.println(offer.get(2));
        offer.put(4, 4);
        System.out.println(offer.get(1));
        System.out.println(offer.get(3));
        System.out.println(offer.get(4));
    }
}
